package com.zzl.myblog.View.Adapter;

import android.view.ViewGroup;


import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import java.util.List;

/**
 *  自定义 TabPagerAdater 实现 FragmentPagerAdapter
 *  viewpager+fragment联动
 *  viewPager.setAdapter(tabPagerAdapter);
 */
public class TabPagerAdapter extends FragmentPagerAdapter {

    private String[] titles;    // 标题数组

    private List<Fragment> fragments = null;    // fragment数组

    public void setTitles(String[] titles) {
        this.titles = titles;
    }

    public void setFragments(List<Fragment> fragments) {
        this.fragments = fragments;
    }

    public TabPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) { // 拿到对应位置的 Fragment
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }   // 返回 fragment 数组长度

    @Override
    public Object instantiateItem(ViewGroup container, int position) {  // 根据 position 初始化Fragment 实例
        return super.instantiateItem(container, position);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) { // 根据 position 销毁 fragment 实例
        super.destroyItem(container, position, object);
    }

    @Override
    public CharSequence getPageTitle(int position) { // 拿到当前 position 的title
        return titles[position];
    }
}
